package com.mewp.permissions.system.service.impl;

import com.mewp.permissions.common.entity.ResultCodeEnum;
import com.mewp.permissions.model.po.SysUser;
import com.mewp.permissions.system.config.CustomUser;
import com.mewp.permissions.system.execption.CustomerException;
import com.mewp.permissions.system.service.SysMenuService;
import com.mewp.permissions.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author mewp
 * @version 1.0
 * @date 2023/8/4 00:24
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getByUserName(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (user.getStatus() == 0) {
            throw new CustomerException(ResultCodeEnum.ACCOUNT_STOP);
        }

        List<String> permsList = menuService.getUserButtonList(user.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String s : permsList) {
            authorities.add(new SimpleGrantedAuthority(s.trim()));
        }
        return new CustomUser(user, authorities);
    }
}
